package com.hellomsg.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * Created by mjitech on 2017/6/24.
 */
@Controller
public class FileDownLowMemoryController {

    @RequestMapping(value = "/downloadlowmemory", method = RequestMethod.GET)
    public void download(HttpServletRequest request, HttpServletResponse response) {

        File file = new File("/Users/mjitech/Downloads/VMware-Fusion-8.5.7-5528452.dmg");

        FileInputStream fis = null;
        OutputStream os = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        try {
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            os = response.getOutputStream();
            bos = new BufferedOutputStream(os);

            response.setContentType("application/octet-stream");

            response.setHeader("Content-Disposition", "attachment; filename=\"usb-1_0-fr-spec.pdf\"");

            try {
                Thread.sleep(5000);
            } catch (Exception e) {

            }

            int c;
            byte[] b = new byte[4096];
            while ((c = bis.read(b)) != -1) {
                bos.write(b, 0, c);
                bos.flush();
            }

            try {
                Thread.sleep(5000);
            } catch (Exception e) {

            }

        }
        catch (IOException e) {
            //throw new ForumException(e);
        }
        finally {
            if (fis != null) {
                try { fis.close(); }
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (bis != null) {
                try { bis.close(); }
                catch (Exception e) {}
            }

            if (os != null) {
                try { os.close(); }
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try { bos.close(); }
                catch (Exception e) {}
            }
        }
    }
}
